import { messages, eventTrack, isSupportScroll, scrollToMyDestination } from "share/common";
import React, {Component} from 'react';
import 'styles/unbox-setting/unbox-setting.scss';
import { Progress, Button, Icon, Modal } from 'antd';
import debounce from 'lodash.debounce';
import {connect} from 'react-redux';
import baseService from 'share/base.service'

import headerBGImg from 'images/home/unbox-setting/head-bg.jpg';
import step1Img from 'images/home/unbox-setting/step1.png';
import step2Img from 'images/home/unbox-setting/step2.png';
import step3Img from 'images/home/unbox-setting/step3.png';
import doneImg from 'images/home/unbox-setting/done.png';
import freeTrialImg from 'images/home/unbox-setting/free-trial.png';
import boughtImg from 'images/home/unbox-setting/bought.png';
import unBoughtImg from 'images/home/unbox-setting/un-bought.png';

import icon1Img from 'images/home/unbox-setting/icon/1.jpg';
import icon2Img from 'images/home/unbox-setting/icon/2.jpg';
import icon3Img from 'images/home/unbox-setting/icon/3.jpg';
import icon4Img from 'images/home/unbox-setting/icon/4.jpg';
import icon5Img from 'images/home/unbox-setting/icon/5.jpg';
import icon6Img from 'images/home/unbox-setting/icon/6.jpg';
import icon7Img from 'images/home/unbox-setting/icon/7.jpg';
import icon8Img from 'images/home/unbox-setting/icon/8.jpg';
import icon9Img from 'images/home/unbox-setting/icon/9.jpg';
import icon10Img from 'images/home/unbox-setting/icon/10.jpg';
import icon11Img from 'images/home/unbox-setting/icon/11.jpg';
import RoleConfig from 'components/template/role-config/role-config';
import FullScreen from 'components/full-screen';
import AdCommon from 'containers/advertisement-page/ad-common';
import menuRoute from 'routes/menuRoute';
import CommonStatus from 'containers/unbox-setting/common-status/common-status';
import backGroundImg from 'images/home/background.jpg';
import { withRouter } from 'react-router'

class UnboxSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showBar: false,
      showAdvertisement: false,
      showFinishStepModal: false,
      BASIC: this.props.settingStatus.filter(item=>item.moduleType === 'BASIC')[0].shortcutList,
      RECOMMEND: this.props.settingStatus.filter(item=>item.moduleType === 'RECOMMEND')[0].shortcutList,
      SENIOR: this.props.settingStatus.filter(item=>item.moduleType === 'SENIOR')[0].shortcutList,
      activeSection: 'Basic', // 'Recommend'  'Advance'
      BasicStatus: {all: 5, activate: 0},
      currentAd: this.props.settingStatus.filter(item=>item.moduleType === 'SENIOR')[0].shortcutList[0],
      RecommendStatus: {all: 9, activate: 0}
    };
    this.codeMap = {
      'W': '',
      'D': 'syncWithDingTalk',
      'Y': 'done',
      'YR': 'done',
      'S': 'freeTrial',
      'YG': 'bought',
      'WG': 'haveNotBought'
    };
    this.step1Finish = false;
    this.step2Finish = false;
    this.scrolling = false;
    this.scrollingFalse = debounce(this.scrollingFalse, 800);
    // this.setMenuCollapse = debounce(this.setMenuCollapse, 100);
    this.categoryMap = {
      'BASIC': '基础设置',
      'RECOMMEND': '推荐设置',
      'SENIOR': '高级功能'
    };
    this.nameMap = {"legalEntity":"法人实体","companyAccount":"公司账户","departmentManage":"部门信息","personManage":"人员信息","roleAuth":"角色授权","expenseType":"费用类型","formSetting":"表单设置","workflow":"审批流","consumptionPlatform":"消费平台","supplierMaintain":"供应商维护","reimbStandard":"报销标准","travelSubsidyStandard":"差补标准","invoiceReceiptFree":"免贴票&免打印","checkInvoice":"发票查验&拍照识别","airfare":"机票比价","intelRcvDocument":"智能收票","intelAudit":"智能审核","bankWithEnt":"银企直联","aliPay":"支付宝支付","intelAccounting":"智能核算","elecArchive":"电子存档","budgetManagement":"预算管理","creditReimb":"信用报销","huabei":"花呗工作花","rebecca":"瑞贝卡"}
  }

  componentWillMount() {
    // 监听浏览器点击返回 (目的 是 打开高级功能全屏广告时 按浏览器返回键 不会从设置中心跳走)
    this.props.router.setRouteLeaveHook(
      this.props.route,
      this.routerWillLeave
    )
  }

  routerWillLeave = (nextLocation) => {
    if (this.state.showAdvertisement) {
      this.setState({showAdvertisement: false})
      return false
    }
  };

  componentDidMount() {
    const { tenantInfo } = this.props;
    // this.setMenuCollapse();
    baseService.getTenantSettingStatus().then((res)=>{
      this.init();
    })
    this.addListener();
    this.findPosition();
    eventTrack({
      category: '快捷设置中心',
      action: '进入快捷设置中心',
      label: tenantInfo.tenantName
    })
  }

  componentWillUnmount() {
    document.removeEventListener('visibilitychange', this.handleVisibilityChange)
  }

  addListener = () => {
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
  }

  findPosition = () => {
    const { location } = this.props;
    let menuKey = location && location.state && location.state.menuKey;
    setTimeout(()=>{
      if (menuKey && menuKey.length && menuKey !== 'Basic') {
        this.handleNavClick(menuKey);
      }
    }, 500)
  }

  handleVisibilityChange = () => {
    if (document.visibilityState === 'hidden') {  //隐藏了

    } else if (document.visibilityState === 'visible') {  //激活了
      baseService.getTenantSettingStatus().then((res)=>{
        this.init(true);
      })
    }
  }

  init = (shouldJudgeSteps) => {
    const { settingStatus } = this.props;
    let BASIC = settingStatus.filter(item=>item.moduleType === 'BASIC')[0];
    let RECOMMEND = settingStatus.filter(item=>item.moduleType === 'RECOMMEND')[0];
    let SENIOR = settingStatus.filter(item=>item.moduleType === 'SENIOR')[0];
    this.setState({
      BASIC: BASIC.shortcutList,
      BasicStatus: {all: BASIC.all, activate: BASIC.activate},
      RECOMMEND: RECOMMEND.shortcutList,
      RecommendStatus: {all: RECOMMEND.all, activate: RECOMMEND.activate},
      SENIOR: SENIOR.shortcutList,
    }, ()=>{
      if (shouldJudgeSteps) {

        // this.setState({showFinishStepModal: true})

        if (BASIC.all === BASIC.activate && !this.step1Finish) {
          this.step1Finish = true;
          this.setState({showFinishStepModal: true})
        } else if (RECOMMEND.all === RECOMMEND.activate && !this.step2Finish) {
          this.step2Finish = true;
          this.setState({showFinishStepModal: true})
        }
      } else {
        if (BASIC.all === BASIC.activate) {
          this.step1Finish = true;
        }
        if (RECOMMEND.all === RECOMMEND.activate) {
          this.step2Finish = true;
        }
      }
    })
  }

  renderTag = (key) => {
    switch (key) {
      case 'done':
        return (
          <div className="tag-done"><img className='tag-img' onMouseDown={e=>e.preventDefault()} src={doneImg} />{messages('basic-1.key162')/*已设置*/}</div>
        )
      case 'syncWithDingTalk':
        return (
          <div className='tag-sync-with-ding-talk'><img className='tag-img' onMouseDown={e=>e.preventDefault()} src={doneImg} />{messages('basic-1.key163')/*钉钉同步*/}</div>
        )
      case 'freeTrial':
        return (
          <div className='tag-free-trial'><img className='tag-img' onMouseDown={e=>e.preventDefault()} src={freeTrialImg} />{messages('basic-1.key77')/*试用中*/}</div>
        )
      case 'bought':
        return (
          <div className='tag-bought'><img className='tag-img' onMouseDown={e=>e.preventDefault()} src={boughtImg} />{messages('basic-1.key164')/*已购买*/}</div>
        )
      case 'haveNotBought':
        return (
          <div className='tag-bought-not'><img className='tag-img' onMouseDown={e=>e.preventDefault()} src={unBoughtImg} />{messages('basic-1.key165')/*未购买*/}</div>
        )
      default:
        return null
    }
  }

  openRoleConfig = (isReadOnly) => {
    this.roleConfigRef.setRoleConfig(true, true, isReadOnly);
  }

  RoleConfigFinish = (reOpenGuide, isFinish) => {
    baseService.getTenantSettingStatus().then((res)=>{
      this.init(true);
    })
  }

  handleOpenWindow = (item, NotZhCn) => {
    const { tenantInfo, language } = this.props;
    eventTrack({
      category: `快捷设置中心+${this.categoryMap[item.moduleType]}+${this.nameMap[item.shortcutCode]}`,
      action: `点击进入该卡片-中控语言：${language.code}`,
      label: tenantInfo.tenantName
    });
    if (NotZhCn && item.moduleType === 'SENIOR') {
      return
    }
    switch (item.pageType) {
      case 'POPUP':
        this.openRoleConfig(item.status === 'YR')
        break;
      case 'LANDING':
        this.setState({
          showAdvertisement: true,
          currentAd: item
        })
        break;
      default:
        window.open(((window.ISIE9 ? "#" : "") + item.shortcutUrl), '_blank')
    }
  }

  renderStep1 = () => {
    const { BASIC } = this.state;
    return (
      <div className='step-one-box'>
        {BASIC.map((item)=>{
          return (
            <div className='single-box' onClick={()=>{this.handleOpenWindow(item)}}>
              <div className="single-title">
                {item.shortcutName}
              </div>
              <div className="single-desc">
                {item.shortcutDesc}
              </div>
              {(item.status === 'W' || item.status === null) && <div className="operation-area">
                <Button type='primary'>{messages('basic-1.key166')/*立即设置*/}</Button>
              </div>}
              <div className="tag">
                {this.renderTag(this.codeMap[item.status || 'W'])}
              </div>
            </div>
          )
        })}
      </div>
    )
  }

  renderStep2 = () => {
    const { RECOMMEND } = this.state;
    return (
      <div className='step-two-box'>
        {RECOMMEND.map((item)=>{
          return (
            <div className='single-box' onClick={()=>{this.handleOpenWindow(item)}}>
              <div className="single-title">
                {item.shortcutName}
              </div>
              <div className="single-desc">
                {item.shortcutDesc}
              </div>
              <div className="tag">
                {this.renderTag(this.codeMap[item.status || 'W'])}
              </div>
            </div>
          )
        })}
      </div>
    )
  }

  renderStep3 = () => {
    const { SENIOR } = this.state;
    const { code } = this.props.language;
    const isZhCn = code === 'zh_cn';

    let map = {
      'intelRcvDocument': icon1Img,
      'intelAudit': icon2Img,
      'bankWithEnt': icon3Img,
      'aliPay': icon4Img,
      'intelAccounting': icon5Img,
      'elecArchive': icon6Img,
      'budgetManagement': icon7Img,
      'creditReimb': icon8Img,
      'huabei': icon9Img,
      'rebecca': icon10Img,
      'airfare': icon11Img
    }
    return (
      <div className='step-three-box'>
        {SENIOR.map((item)=>{
          return (
            <div className={`single-box ${isZhCn ? 'hover' : ''}`} onClick={()=>{this.handleOpenWindow(item, !isZhCn)}}>
              <div className="img-box">
                <img onMouseDown={e=>e.preventDefault()} className='advance-img' src={map[item.shortcutCode]} />
              </div>
              <div className="info-box">
                <div className={`single-title ${code}`}>
                  {item.shortcutName}
                </div>
                <div className={`single-desc ${code}`}>
                  {item.shortcutDesc}
                </div>
              </div>
            </div>
          )
        })}
      </div>
    )
  }

  handleNavClick = (key) => {
    let map = {
      'Basic': this.section1Ref,
      'Recommend': this.section2Ref,
      'Advance': this.section3Ref
    }
    this.scrolling = true;
    this.scrollingFalse();
    scrollToMyDestination(this.unboxSettingPage, (key === 'Basic' ? map[key].offsetTop - 70 : map[key].offsetTop - 64))
    this.setState({activeSection: key, showBar: true})
  }

  onScrollPage = (key) => {
    if (!this.scrolling) {
      if (this.unboxSettingPage.scrollTop > 177) {
        this.setState({showBar: true})
      } else {
        this.setState({showBar: false})
      }
      if (this.unboxSettingPage.scrollTop > (this.section3Ref.offsetTop - 64)) {
        this.setState({activeSection: 'Advance'})
      } else if (this.unboxSettingPage.scrollTop > (this.section2Ref.offsetTop - 64)) {
        this.setState({activeSection: 'Recommend'})
      } else if (this.unboxSettingPage.scrollTop <= 177) {
        this.setState({activeSection: 'Basic'})
      }
    }
  }

  scrollingFalse = () => {
    this.scrolling = false;
  }

  onWheelHandle = () => {
    this.scrolling = false;
  }

  goToMyHome = () => {
    const {user, menuTree} = this.props;
    let url = menuTree.keyUrl['home'] || menuRoute.getPageUrlByKey('dashboard');
    /*每个人默认展示个人仪表盘。有管理员权限的展示管理员首页*/
    if (!url) {
      /*超强大容错。找menuTree的前20个菜单，找到URL就停止。避免登录后前面菜单没有URL无法登录进去。
       容错强大容易漏掉bug，只要进去的不是第一个菜单，就说明有问题，开发者请注意排查。*/
      for (let i = 0; i < 20; i++) {
        url = getUrl(menuTree.menuTree[i]);
        if (url) break;
      }
    }
    // configureStore.store.dispatch(setMenuCollapse(false));
    this.context.router.push(url);
    // window.showNewUnboxTip();
    function getUrl (menu) {
      return menu.subMenuTree && menu.subMenuTree.length ? getUrl(menu.subMenuTree[0]) : menu.url;
    }
  }

  goToMyStep = (key, judgeWitch) => {
    if (judgeWitch) {
      if (this.step1Finish && this.step2Finish) {
        this.setState({showFinishStepModal: false}, ()=>{
          this.handleNavClick('Advance');
        })
      } else if (this.step1Finish) {
        this.setState({showFinishStepModal: false}, ()=>{
          this.handleNavClick('Recommend');
        })
      } else if (this.step2Finish) {
        this.setState({showFinishStepModal: false}, ()=>{
          this.handleNavClick('Basic');
        })
      }
    } else {
      this.setState({showFinishStepModal: false}, ()=>{
        this.handleNavClick(key);
      })
    }
  }

  render() {
    const { activeSection, showBar, BasicStatus, RecommendStatus, showAdvertisement,
      currentAd, showFinishStepModal, RECOMMEND } = this.state;
    const { menuCollapse } = this.props;
    const { code } = this.props.language;
    const isZhCn = code === 'zh_cn';
    const isSupport = isSupportScroll(this.unboxSettingPage);
    let finishFirstTwo = BasicStatus.all === BasicStatus.activate && RecommendStatus.all === RecommendStatus.activate;
    let RECOMMENDFirstTwoArray = RECOMMEND.filter(item=>(item.shortcutCode === 'expenseType' || item.shortcutCode === 'formSetting'));
    let finishedOne = RECOMMENDFirstTwoArray[0].status === 'Y', finishedTwo = RECOMMENDFirstTwoArray[1].status === 'Y';

    return (
      <div className='unbox-setting' ref={ref => this.unboxSettingPage = ref} onScroll={this.onScrollPage} onWheel={this.onWheelHandle}>
        <div className="head-box">
          <div className="unbox-head-box-content">
            <div className="title">{messages('basic-1.key167')/*欢迎来到快捷设置中心*/}</div>
            <div className="desc">{messages('basic-1.key168')/*让您更高效的管理账户*/}</div>
            <div className={`navigation-box ${showBar ? (menuCollapse ? 'show-bar collapse-width' : 'show-bar un-collapse-width') : ''}`}>
              <div className="single-nav" >
                <div
                  className={`nav-title ${activeSection === 'Basic' ? 'active' : ''}`}
                  onClick={()=> isSupport && this.handleNavClick('Basic')}
                  style={{cursor: isSupport ? 'pointer' : 'default'}}
                >
                  {messages('basic-1.key155')/*基础设置*/}
                </div>
              </div>
              <div className="single-nav">
                <div
                  className={`nav-title ${activeSection === 'Recommend' ? 'active' : ''}`}
                  onClick={()=> isSupport && this.handleNavClick('Recommend')}
                  style={{cursor: isSupport ? 'pointer' : 'default'}}
                >
                  {messages('basic-1.key157')/*推荐设置*/}
                </div>
              </div>
              <div className="single-nav">
                <div
                  className={`nav-title ${activeSection === 'Advance' ? 'active' : ''}`}
                  onClick={()=>this.handleNavClick('Advance')}
                  style={{cursor: isSupport ? 'pointer' : 'default'}}
                >
                  {messages('basic-1.key159')/*高级功能*/}
                </div>
              </div>
            </div>
            <div className="setting-one" ref={ref => this.section1Ref = ref}>
              <div className="main-info-flex-box">
                <div className="info-left">
                  <div className="step-number">
                    <img className='number-img' src={step1Img} onMouseDown={e=>e.preventDefault()} />
                  </div>
                  <div className="step-title-wrapper">
                    <div className="step-title">
                      {messages('basic-1.key155')/*基础设置*/}
                    </div>
                    <div className="step-desc">
                      {
                        BasicStatus.activate === BasicStatus.all ?
                          messages('basic-1.key169')/*恭喜您，完成基础设置*/ :
                          messages('basic-1.key156')/*该模块为必填设置，请尽快完成设置*/
                      }
                    </div>
                  </div>
                  {BasicStatus.activate === BasicStatus.all && <div className="lets-start" onClick={this.goToMyHome}>
                    {messages('helios.login.try.now')/*立即体验*/}
                  </div>}
                </div>
                <div className="step-right">
                  <div className="step-top">
                    <div className="step-title">
                      {BasicStatus.activate === 0 ?
                        messages('basic-1.key170',{arg1: BasicStatus.all})/*共{arg1}个必填设置，完成后即可使用*/ :
                        (
                          BasicStatus.activate !== BasicStatus.all ?
                            messages('basic-1.key171',{arg1: BasicStatus.activate,arg2: BasicStatus.all-BasicStatus.activate})/*已完成{arg1}个必填设置，还差{arg2}个即可使用*/ :
                            messages('basic-1.key172')/*已完成必填设置*/
                        )
                      }
                    </div>
                    <div className={`one-in-all ${BasicStatus.activate !== 0 && 'blue-style'}`}>
                      {`${BasicStatus.activate} / ${BasicStatus.all}`}
                    </div>
                  </div>
                  <Progress percent={(BasicStatus.activate/BasicStatus.all)*100} showInfo={false} />
                </div>
              </div>
              {this.renderStep1()}
            </div>
          </div>
          <div className="unbox-background-img" style={{backgroundImage: `url('${headerBGImg}')`}} />
        </div>
        <div className="other-box">
          <div className="setting-two" ref={ref => this.section2Ref = ref}>
            <div className="main-info-flex-box">
              <div className="info-left">
                <div className="step-number">
                  <img className='number-img' src={step2Img} onMouseDown={e=>e.preventDefault()} />
                </div>
                <div className="step-title-wrapper">
                  <div className="step-title">
                    {messages('basic-1.key157')/*推荐设置*/}
                  </div>
                  <div className="step-desc">
                    {messages('basic-1.key158')/*可以更好地帮助您的企业管控费用*/}
                  </div>
                </div>
              </div>
              <div className="step-right">
                <div className="step-top">
                  <div className="step-title">
                    {RecommendStatus.activate === 0 ?
                      messages('basic-1.key173')/*暂未开始推荐设置*/:
                      (
                        RecommendStatus.activate === 1 && (finishedOne || finishedTwo) ?
                          (finishedOne ? messages('basic-1.key174')/*已初始化费用类型*/ : messages('basic-1.key175')/*已初始化表单设置*/) :
                          (
                            RecommendStatus.activate === 2 && (finishedOne && finishedTwo) ?
                              messages('basic-1.key176')/*已初始化费用类型，表单设置*/ :
                              (RecommendStatus.activate !== RecommendStatus.all ?
                                messages('basic-1.key177',{arg1: RecommendStatus.activate})/*已完成{arg1}个推荐设置*/ :
                                messages('basic-1.key178')/*已完成推荐设置*/)
                          )
                      )
                    }
                  </div>
                  <div className={`one-in-all ${RecommendStatus.activate !== 0 && 'blue-style'}`}>
                    {`${RecommendStatus.activate} / ${RecommendStatus.all}`}
                  </div>
                </div>
                <Progress percent={(RecommendStatus.activate/RecommendStatus.all)*100} showInfo={false} />
              </div>
            </div>
            {this.renderStep2()}
          </div>
        </div>
        <div className="other-box">
          <div className="setting-three" ref={ref => this.section3Ref = ref}>
            <div className="main-info-flex-box">
              <div className="info-left">
                <div className="step-number">
                  <img className='number-img' src={step3Img} onMouseDown={e=>e.preventDefault()} />
                </div>
                <div className="step-title-wrapper">
                  <div className="step-title">
                    {messages('basic-1.key159')/*高级功能*/}
                  </div>
                  <div className="step-desc">
                    {messages('basic-1.key160')/*全面提升员工报销体验与运营管理效率*/}
                  </div>
                </div>
              </div>
              {!isZhCn && <div className="contact-right">
                <div className="first-line">
                  <span className="desc">{messages('basic-1.key179')/*联系您的客服经理或拨打咨询电话*/}</span>
                  <a className="phone-num-a" href="tel:4008297878">400-829-7878</a>
                </div>
                <div className="second-line">
                  <span className='sub-text'>{messages('basic-1.key152')/*周一至周日 9:00 ~ 18:00*/}</span>
                </div>
              </div>}
            </div>
            {this.renderStep3()}
          </div>
        </div>

        {/*中控管理员初始化配置引导模态框*/}
        <RoleConfig
          onRef={ref => this.roleConfigRef = ref}
          onFinish={(reOpenGuide, isFinish)=>{this.RoleConfigFinish(reOpenGuide, isFinish)}}
        />

        {showAdvertisement &&
        <FullScreen animateIn="fadeIn" animateOut="fadeOut" style={{ background: '#FFFFFF' }}>
          <AdCommon onCancel={()=>{this.setState({showAdvertisement: false})}} currentAd={currentAd} />
        </FullScreen>}

        <Modal
          className={`ant-new-welcome-modal ${['zh_cn', 'zh_tw'].indexOf(code) !== -1 ? '' : 'en'}`}
          width={['zh_cn', 'zh_tw'].indexOf(code) !== -1 ? 600 : 690}
          visible={showFinishStepModal}
          footer={null}
          maskClosable={false}
          onCancel={()=>{this.setState({showFinishStepModal: false})}}
        >
          <div className="new-welcome-modal">
            <div className="content">
              <div className={`main-title ${!finishFirstTwo && 'need-bottom'}`}>{finishFirstTwo ? messages('basic-1.key180')/*恭喜您，完成全部设置*/ : messages('basic-1.key181')/*恭喜您，完成以下设置*/}</div>
              <div className="text">
                <div>{finishFirstTwo ? messages('basic-1.key182')/*您可以继续了解高级功能*/ : ''}</div>
              </div>
              <div className="step-2">
                <div className="guide-wrapper">
                  <CommonStatus noStep goToUnboxSetting={(key)=>{this.goToMyStep(key)}} />
                </div>
                <Button type='primary' className={`start-btn`} onClick={()=>{this.goToMyStep(null, true)}} >
                  {finishFirstTwo ? messages('basic-1.key183')/*了解高级功能*/ : messages('basic-1.key184')/*继续完成配置*/}
                </Button>
                <span className='nope-lets-start' onClick={this.goToMyHome}>{messages('basic-1.key185')/*不，直接体验*/}</span>
              </div>
            </div>
            <img onMouseDown={e=>e.preventDefault()} src={backGroundImg} className='background-image'/>
          </div>
        </Modal>

      </div>
    );
  }
}

UnboxSetting.contextTypes = {
  router: React.PropTypes.object
};

UnboxSetting.propTypes = {};

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant,
    settingStatus: state.login.settingStatus,
    menuTree: state.login.menuTree,
    user: state.login.user,
    language: state.main.language,
    menuCollapse: state.main.menuCollapse,
  }
}

export default withRouter(connect(mapStateToProps)(UnboxSetting));
